"""废料 API Router"""
from typing_extensions import Annotated

from fastapi import APIRouter, Depends, Request

from core.database import db_session
from core.formclass import WriteCommentForm
from core.models import Board, Member, Scrap, WriteBaseModel
from lib.board_lib import insert_board_new, set_write_delay
from lib.common import get_paging_info

from api.v1.service.point import PointServiceAPI
from api.v1.dependencies.board import get_board, get_write
from api.v1.dependencies.member import get_current_member
from api.v1.dependencies.scrap import (
    get_scrap, validate_create_scrap, validate_delete_scrap
)
from api.v1.service.scrap import ScrapServiceAPI
from api.v1.service.board import CommentServiceAPI
from api.v1.models.pagination import PagenationRequest
from api.v1.models.response import (
    MessageResponse, response_401, response_403, response_404, response_409,
    response_422, response_500,
)
from api.v1.models.scrap import CreateScrap, ScrapFormResponse, ScrapListResponse

router = APIRouter()


@router.get("/scraps",
            summary="会员报废清单查询",
            responses={**response_401, **response_403,
                       **response_422, **response_500})
async def read_member_scraps(
    service: Annotated[ScrapServiceAPI, Depends()],
    member: Annotated[Member, Depends(get_current_member)],
    data: Annotated[PagenationRequest, Depends()]
) -> ScrapListResponse:
    # “查看会员剪贴簿列表。”
    total_records = service.fetch_total_records(member)
    paging_info = get_paging_info(data.page, data.per_page, total_records)
    scraps = service.fetch_scraps(member,data.offset, data.per_page)
    scraps = service.set_subjects(scraps)

    return {
        "total_records": total_records,
        "total_pages": paging_info["total_pages"],
        "scraps": scraps
    }


@router.get("/scraps/{bo_table}/{wr_id}",
            dependencies=[Depends(get_current_member),
                          Depends(validate_create_scrap)],
            summary="会员报废登记页面设置查询",
            responses={**response_403, **response_404, **response_409})
async def scrap_form_api(
    board: Annotated[Board, Depends(get_board)],
    write: Annotated[WriteBaseModel, Depends(get_write)],
) -> ScrapFormResponse:
    """
    我们在废料注册页面上查找信息.
    - 公告板信息
    - 关于帖子的信息
    """
    return {
        "board": board,
        "write": write,
    }


@router.post("/scraps/{bo_table}/{wr_id}",
             dependencies=[Depends(validate_create_scrap)],
             summary="注册会员剪贴簿",
             responses={**response_401, **response_403,
                        **response_409, **response_422})
async def create_member_scrap(
    request: Request,
    db: db_session,
    service: Annotated[ScrapServiceAPI, Depends()],
    comment_service: Annotated[CommentServiceAPI, Depends(CommentServiceAPI.async_init)],
    member: Annotated[Member, Depends(get_current_member)],
    board: Annotated[Board, Depends(get_board)],
    write: Annotated[WriteBaseModel, Depends(get_write)],
    data: CreateScrap
) -> MessageResponse:
    """
注册会员剪贴簿。
-注册剪报将增加剪报计数。
-写评论的话，评论也会一起注册。

### Request Body
-**wr_content**：添加剪贴时，要一起注册的评论内容
    """
    bo_table = board.bo_table
    wr_id = write.wr_id

    #生成评论
    if data.wr_content:
        db.refresh(member)
        form = WriteCommentForm(w="w", wr_id=wr_id, wr_content=data.wr_content,
                                wr_name=None, wr_password=None, wr_secret=None,
                                comment_id=0)
        comment_service.validate_write_delay()  #保证是在规定的时间内没有二次重写；防止频繁掉用API；
        comment_service.validate_comment_level()
        comment_service.validate_point()
        comment_service.validate_post_content(data.wr_content)  #是否有恶意评论；
        comment_service.validate_comment_password(form.wr_password)
        comment = comment_service.save_comment(form, write)
        comment_service.add_point(comment)
        comment_service.send_write_mail_(comment, write)
        insert_board_new(bo_table, comment)
        set_write_delay(request)

    service.create_scrap(member, bo_table, wr_id)
    service.update_scrap_count(member)

    return {"message": "添加了剪报。"}


@router.delete("/scraps/{ms_id}",
               dependencies=[Depends(validate_delete_scrap)],
               summary="删除成员废料",
               responses={**response_401, **response_403, **response_404})
async def delete_member_scrap(
    service: Annotated[ScrapServiceAPI, Depends()],
    member: Annotated[Member, Depends(get_current_member)],
    scrap: Annotated[Scrap, Depends(get_scrap)]
) -> MessageResponse:
    """
    删除成员废料.
    - 删除废料会减少废料计数.
    """
    service.delete_scrap(scrap)
    service.update_scrap_count(member)

    return {"message": "你已经删除了废料."}
